<template>
    <div class="prescriptionIssuance">
        <div class="top">
            <div class="left-top">
                <el-popover :visible="visible" placement="bottom" :width="200">
                    <div v-for="(v, i) in drugslist" :key="i">
                        <div @click="choiceBtn(v)">{{ v.drugsname }}</div>
                    </div>
                    <template #reference>
                        <el-input @input="inpChange" v-model="addInput" style="width: 200px;margin-right: 20px;"
                            size="small" placeholder="林" />
                    </template>

                </el-popover>
                <el-button type="primary" @click="addBtn">添加药品</el-button>
            </div>
            <div class="right-top" @click="delSelBtn"><el-button>删除选中</el-button></div>
        </div>

        <el-table :data="tableData" stripe style="width: 100%" @selection-change="selectionChange">
            <el-table-column type="selection" />
            <el-table-column prop="drugsname" label="商品名" />
            <el-table-column label="商品图" width="80">
                <template #default="scope">
                    <img :src=scope.row.img alt="">
                </template>
            </el-table-column>
            <el-table-column prop="type" label="规格" />
            <el-table-column prop="price" label="单价" />
            <el-table-column label="数量" width="200">
                <template #default="scope">
                    <el-input-number v-model="scope.row.count" />
                </template>
            </el-table-column>
            <el-table-column prop="endtime" label="有效期" width="180" />
            <el-table-column label="用量备注" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.other" size="small" />
                </template>
            </el-table-column>

            <el-table-column label="操作" width="80">
                <template #default="scope">
                    <el-button @click="delBtn(scope.row)" type="danger" :icon="Delete"> 删除按钮</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="bot">
            <el-button type="primary" @click="addAllBtn">开具处方</el-button> <el-button>张智</el-button>
            <div class="name">医生签名:</div>
            <div class="all-price">总价：{{ price }}</div>
        </div>
    </div>
</template>

<script setup lang="ts">
// 转字符串数组
import qs from 'qs'
// 对
import dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // 导入插件
import 'dayjs/locale/zh-cn' // 导入本地化语言


import { ref, reactive, computed, nextTick, watchEffect, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'


// 模糊查询 开具处方
import { recipelDrugsSearch, recipelAdd } from '../../../api/medicalFrontline/medicalFrontlineApi'
const addInput = ref('')
const visible = ref(false)
// 药品列表
let drugslist = reactive([])
// / 总价 
let price = ref(0)
// input模糊查询 药品
const inpChange = (async () => {
    visible.value = false
    console.log(addInput.value);
    let res = await recipelDrugsSearch({ name: addInput.value })
    console.log(res.data.data);
    try {
        drugslist = res.data.data
        if (res.data.data.length > 0) visible.value = true
        else visible.value = false
    } catch {
        visible.value = false
    }
})


// 点击模糊查询单项
let itemObj: any = reactive({})
const choiceBtn = (item) => {
    visible.value = false
    itemObj = item
    addInput.value = item?.drugsname
    console.log(itemObj);
}
const tableData = reactive([
])

// 封装添加药品
const addFn = () => {
    // dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
    itemObj!.endtime = dayjs(itemObj!.endtime).format(' YYYY-MM-DD')
    tableData.unshift(itemObj)
    console.log(itemObj.endtime);
    // 赋值为空
    itemObj = {}
    // 关闭 模糊查询框
    visible.value = false
    ElMessage.success('恭喜您，数据添加成功')
}
// 添加药品
const addBtn = () => {

    // itemObj不为空 tableData为空 直接push
    if (JSON.stringify(itemObj) != "{}") {
        console.log('addInput', { ...itemObj });
        addFn()

    } else {

        tableData.forEach((v) => {
            console.log('vvvvv', v);
            if (v == itemObj || JSON.stringify(itemObj) == "{}") {
                ElMessage.error('亲，数据重复了')
            } else {
                // itemObj不为空 tableData 直接push
                addFn()
            }
        })
    }
}

// itemObj= {}
// 选择药品
let state = reactive({
    selectList: []
})
const selectionChange = (selection) => {
    state.selectList = selection
    console.log(state.selectList);
    // 总价归0
    price.value = 0

}
// 
// 批量删除
const delSelBtn = () => {
    console.log("item");
    ElMessageBox.confirm(
        '您正在删除处方药品，此操作不可逆，确定删除吗',
        '系统提示',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            console.log("1", state.selectList);
            console.log("2", state.selectList);
            // 删除 table 选中的数据
            let indexArr = ref([])
            tableData.forEach((v, i) => {
                state.selectList.forEach((item, index) => {
                    if (v.id == item.id) {
                        // tableData.slice(i,1)
                        indexArr.value.push(i)
                        console.log(v.id, item.id);

                    }
                })
            })
            console.log("indexArr",indexArr);
            
            tableData.forEach((v, i) => {
                indexArr.value.forEach((item, index) => {
                    tableData.splice(item, 1)
                })
            })
            console.log('tableData', tableData);
            // 选择数据清空
            state.selectList = []
            // 总价清空
            price.value = 0
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
// 单个删除按钮
const delBtn = (item) => {
    console.log("item", item);
    ElMessageBox.confirm(
        '您正在删除处方药品，此操作不可逆，确定删除吗',
        '系统提示',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            console.log(item.id);
            // console.log('',state.selectList);
            // 表格删除
            let index = tableData.findIndex((v, i) => {
                console.log(item.id, v.id);

                return item.id == v.id
            })

            tableData.splice(index, 1)
            console.log('表格 需要删除的项', index);
            // 选择项 需要删除项
            let index1 = state.selectList.findIndex((v, i) => {
                console.log(item.id, v.id);
                return item.id == v.id
            })

            state.selectList.splice(index, 1)
            console.log('表格 需要删除的项', index);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
// 总价--不只是在页面中 不能使用计算属性
// let price = computed(() => {
//     let price = 0
//     state.selectList.forEach((v, i) => {
//         price += (v.price * v.count)
//     })
//     return price
// })
watch(() => state.selectList, (newVal, oldVal) => {
    // 总价清0 
    price.value=0
    // 重新计算
    console.log('newVal', newVal);
    newVal.forEach((v, i) => {
        price.value += v.price * v.count
    })
}, { deep: true })

// 开具处方
const addAllBtn = (async () => {
    let res = await recipelAdd({
        doctorid: 11,
        recipel: qs.stringify(state.selectList),
        price: price.value
    })
    // debugger
    console.log(res.data);
})



</script>

<style scoped>
.prescriptionIssuance {
    padding: 20px;
}

.top {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
}

/* 弹窗 */
.el-message-box__btns {
    display: flex;
    justify-content: space-between !important;
}

.bot {
    margin-top: 30px;
    display: flex;
    flex-direction: row-reverse;
}

.name {
    line-height: 32px;
    margin-right: 40px;
}

.all-price {
    line-height: 32px;
    margin-right: 100px;
}

.el-button {
    margin-right: 32px;
}

img {
    width: 80px;
}
</style>